package com.btpj.shop.service.impl;

import com.btpj.shop.dao.BannerMapper;
import com.btpj.shop.dto.BannerDto;
import com.btpj.shop.dto.param.BannerParam;
import com.btpj.shop.entity.Banner;
import com.btpj.shop.entity.User;
import com.btpj.shop.service.BannerService;
import com.btpj.shop.service.UserService;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class BannerServiceImpl implements BannerService {

    @Resource
    private BannerMapper bannerMapper;

    @Resource
    private UserService userService;

    @Override
    public boolean addBanner(BannerParam bannerParam) {
        Banner banner = new Banner();
        BeanUtils.copyProperties(bannerParam, banner);
        User currentUser = userService.getUserInfo();
        banner.setCreateUser(currentUser.getId());
        banner.setUpdateUser(currentUser.getId());
        return bannerMapper.insertSelective(banner) > 0;
    }

    @Override
    public boolean exists(Long id) {
        return bannerMapper.selectByPrimaryKey(id) != null;
    }

    @Override
    public boolean updateBanner(Long id, BannerParam bannerParam) {
        Banner banner = bannerMapper.selectByPrimaryKey(id);
        BeanUtils.copyProperties(bannerParam, banner);
        return bannerMapper.updateByPrimaryKeySelective(banner) > 0;
    }

    @Transactional
    @Override
    public boolean deleteBanners(Long[] ids) {
        return bannerMapper.deleteByIds(ids) > 0;
    }

    @Override
    public List<BannerDto> getBannerDtoList() {
        List<Banner> banners = bannerMapper.getBannerList();
        return banners.stream().map(Banner::banner2Dto).collect(Collectors.toList());
    }
}
